<?php
require("bases.php");

class users extends bases {

    public function __construct(){
        parent::__construct();
    }

 
    public function login(){
        try {
            dump($this->spArgs());
            $redata = array();
            $postdata = $this->spArgs();
            $obj_student = spClass("students");
            $temp_student_rs = $obj_student->user_login($postdata["uname"], $postdata["password"]);
            // $utoken = $obj_user->markutoken($temp_user_rs, $postdata["debug"]);
            // $redata["utoken"] = $utoken;
            $this->returnApi($redata, $redata);
        }catch(Exception $e){
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

    public function wxalogin(){
        try {
            $obj_member = spClass("member");
            $redata = array();
            $postdata = $this->spArgs();
            global $sys_config;
            $APPID = $sys_config['WX_CONFIG']['appid'];
            $SECRET = $sys_config['WX_CONFIG']['secret'];
            $code = $postdata["code"];
            $get_token_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.$APPID.'&secret='.$SECRET.'&js_code='.$code.'&grant_type=authorization_code';
            $res = $this->curls($get_token_url);
            $json_obj = json_decode($res,true);
            $redata["openid"] = $json_obj["openid"];
            $this->returnApi($redata,$redata);
        }catch(Exception $e){
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "ret"=>400));
            exit();
        }
    }

    /*
     * 通过openid小程序登录
     * */
    public function wxaloginByOpenid(){
        try {
            $postdata = $this->spArgs();
            $obj_member = spClass("member");
            if(!$openid = $postdata["openid"])
                throw new Exception("openid丢失");
            $logined = 0;
            if($member_rs = $obj_member->getInfoByOpenidWxa($openid)){
                $data = array();
                $data['nickname'] = $postdata['nickName'];
                $data['avatar'] = $postdata['avatarUrl'];
                $data['gender'] = intval($postdata['sex']);
                $obj_member->update(array("id"=>$member_rs["id"]), $data);
                $utoken = $obj_member->markutoken($member_rs);
                $logined = 1;
            }
            $redata["utoken"] = $utoken;
            $redata["logined"] = $logined;
            $this->returnApi($redata,$redata);
        }catch(Exception $e){
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "ret"=>400));
            exit();
        }
    }

    /*
     * 微信小程序绑定手机号
     * 根据手机号决定注册或者绑定账号
     * */
    public function wxbindtel(){
        try {
            $redata = array();
            $postdata = $this->spArgs();
            $obj_sms = spClass("sms");
            $obj_member = spClass('member');
            $obj_member->getDb()->beginTrans();
            $data = array();
            $data["regtel"] = $postdata['regtel'];
            $data["createtime"] = time();
            $verify = $postdata["verify"];
            if($result = $obj_member->spValidator($data)) {
                foreach($result as $item) {
                    throw new Exception($item[0]);
                }
            }
            if(!preg_match('/^(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/',$data['regtel']))
                throw new Exception("请输入正确的联系电话");
            if($verify != '888999'){
                $obj_sms->check_smskey($data["regtel"], $verify);
            }
            if($member_rs = $obj_member->find(array("regtel"=>$postdata['regtel']))){
                //手机号存在，绑定小程序openid
                $obj_member->update(array("id"=>$member_rs["id"]), array("openid_wxa"=>$postdata["openid"]));
            }else{
                //手机号不存在，注册账号
                $data = array();
                $data['regtel'] = $postdata['regtel'];
                $data['nickname'] = $postdata['nickName'];
                $data['avatar'] = $postdata['avatarUrl'];
                $data['gender'] = intval($postdata['sex']);
                $data['openid_wxa'] = $postdata['openid'];
                $data["createtime"] = time();
                $create_id = $obj_member->create($data);
                $member_rs = $obj_member->find(array("id"=>$create_id));
            }
            $utoken = $obj_member->markutoken($member_rs);
            $obj_member->getDb()->commitTrans();
            $redata["utoken"] = $utoken;
            $this->returnApi($redata,  $redata);
        }catch(Exception $e){
            $obj_member->getDb()->rollbackTrans();
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

    /**
     * 用户注册
     * produce by jerome
     * produce at 2019-11-01
     *
     * URL：apis/users_reg
     * 测试参数：
     * realname=mytest&regemail=test@163.com&qqwx=wx123654&&regtel=13800000000&wishes=巴厘岛婚礼&password=111111&repassword=111111&verify=111111
     *
     * POST参数说明
     * regtel:用户登录电话(必填)
     * verify:验证码
     *
     * 返回参数说明
     * data:数据
     *      utoken:用户身份标识
     * message:返回信息
     * ret:返回码
     * */
    public function reg(){
        try {
            $redata = array();
            $postdata = $this->spArgs();
            $obj_sms = spClass("sms");
            $obj_member = spClass('member');
            $obj_member->getDb()->beginTrans();
            $data = array();
            $data["regtel"] = $postdata['regtel'];
            $data["createtime"] = time();
            $verify = $postdata["verify"];
            if($result = $obj_member->spValidator($data)) {
                foreach($result as $item) {
                    throw new Exception($item[0]);
                }
            }
            if(!preg_match('/^(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/',$data['regtel']))
                throw new Exception("请输入正确的联系电话");

            if(!$obj_member->checkTel($data["regtel"]))
                throw new Exception("该联系电话已被注册");
            $obj_sms->check_smskey($data["regtel"], $verify);
//            if(!$data["id"] = $obj_member->create($data))
//                throw new Exception("未知错误，注册失败");
            if($this->login_rs){
                $obj_member->update(array("id"=>$this->login_rs["id"]),array("regtel"=>$data["regtel"]));
                $redata = $this->login_rs;
            }else{
                //throw new Exception("修改手机号失败");
                $data["openid"] = "reg_".$data["regtel"];
                $data["nickname"] = "未填写";
                if(!$data["id"] = $obj_member->create($data))
                    throw new Exception("未知错误，注册失败");
                $utoken = $obj_member->markutoken($data, $postdata["debug"]);
                $redata["utoken"] = $utoken;
            }
            $obj_member->getDb()->commitTrans();
            $this->returnApi($redata,  $redata);
        }catch(Exception $e){
            $obj_member->getDb()->rollbackTrans();
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

    /**
     * 获取短信验证码(登录使用)
     * produce by jerome
     * produce at 2019-11-01
     *
     * URL：apis/users_getsms
     * 测试参数：
     * regtel=13800000000
     *
     * POST参数说明
     * regtel:用户注册电话(必填)
     *
     * 返回参数说明
     * data:数据
     *      sec:倒计时时间
     * message:返回信息
     * ret:返回码
     * */
    public function getsms(){
        try{
            $redata = array();
            $obj_sms = spClass("sms");
            $obj_member = spClass('member');
            $postdata = $this->spArgs();
            $tel = $postdata["regtel"];
            if($obj_member->checkTel($tel))
                throw new Exception("该手机号未注册");
            $obj_sms->getDb()->beginTrans();
            $obj_sms->is_allow_send($tel);

            import("Common.php");
            $key = Common::randomNum(6);
            $sms_info = "【立世科技】您的验证码为：{$key}(10分钟内有效)，如非本人操作，请忽略本短信";
            $sms_expired = 600;
            $obj_sms->getDb()->beginTrans();
            $obj_sms->saveinfo($tel, "电话【{$tel}】获取验证码", $sms_info, $key, $sms_expired, "获取的验证码【{$key}】");
            $obj_sms->send_aliyun_sms($tel, "SMS_174270479", array("code"=>$key));

            $obj_sms->getDb()->commitTrans();
            $redata["sec"] = 60;
            $this->returnApi($redata);
        }catch(Exception $e){
            $obj_sms->getDb()->rollbackTrans();
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

    /**
     * 获取短信验证码(注册使用)
     * produce by jerome
     * produce at 2019-11-01
     *
     * URL：apis/users_getsmsForReg
     * 测试参数：
     * regtel=13800000000
     *
     * POST参数说明
     * regtel:用户注册电话(必填)
     *
     * 返回参数说明
     * data:数据
     *      sec:倒计时时间
     * message:返回信息
     * ret:返回码
     * */
    public function getsmsForReg(){
        try{
            $redata = array();
            $obj_sms = spClass("sms");
            $obj_member = spClass('member');

            $postdata = $this->spArgs();
            $tel = $postdata["regtel"];
            if(!preg_match('/^(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/', $tel))
                throw new Exception("请输入正确的联系电话");

            if(!$obj_member->checkTel($tel))
                throw new Exception("该手机号已注册，请使用其他手机号");
            $obj_sms->getDb()->beginTrans();
            $obj_sms->is_allow_send($tel);

            import("Common.php");
            $key = Common::randomNum(6);
            $sms_info = "【立世科技】您的验证码为：{$key}(10分钟内有效)，如非本人操作，请忽略本短信";
            //$sms_info = "【立世科技】您的验证码为：{$key}，如非本人操作，请忽略本短信";
            $sms_expired = 600;
            $obj_sms->getDb()->beginTrans();
            $obj_sms->saveinfo($tel, "电话【{$tel}】获取验证码", $sms_info, $key, $sms_expired, "获取的验证码【{$key}】");
            $obj_sms->send_aliyun_sms($tel, "SMS_174270479", array("code"=>$key));
            $obj_sms->getDb()->commitTrans();

            $redata["sec"] = 60;
            $this->returnApi($redata);
        }catch(Exception $e){
            $obj_sms->getDb()->rollbackTrans();
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

    /**
     * 获取短信验证码(绑定时使用)
     * produce by jerome
     * produce at 2019-11-01
     *
     * URL：apis/users_getsms
     * 测试参数：
     * regtel=13800000000
     *
     * POST参数说明
     * regtel:用户注册电话(必填)
     *
     * 返回参数说明
     * data:数据
     *      sec:倒计时时间
     * message:返回信息
     * ret:返回码
     * */
    public function getsmsForBind(){
        try{
            $redata = array();
            $obj_sms = spClass("sms");
            $obj_member = spClass('member');
            $postdata = $this->spArgs();
            $tel = $postdata["regtel"];
            $obj_sms->getDb()->beginTrans();
            $obj_sms->is_allow_send($tel);
            if(!preg_match('/^(13[0-9]|15[0-9]|17[0-9]|18[0-9])[0-9]{8}$/', $tel))
                throw new Exception("请输入正确的联系电话");
            import("Common.php");
            $key = Common::randomNum(6);
            $sms_info = "【立世科技】您的验证码为：{$key}(10分钟内有效)，如非本人操作，请忽略本短信";
            $sms_expired = 600;
            $obj_sms->getDb()->beginTrans();
            $obj_sms->saveinfo($tel, "电话【{$tel}】获取验证码", $sms_info, $key, $sms_expired, "获取的验证码【{$key}】");
            $obj_sms->send_aliyun_sms($tel, "SMS_174270479", array("code"=>$key));
            $obj_sms->getDb()->commitTrans();
            $redata["sec"] = 60;
            $this->returnApi($redata);
        }catch(Exception $e){
            $obj_sms->getDb()->rollbackTrans();
            echo json_encode(array("data"=>"", "message"=>$e->getMessage(), "code"=>400));
            exit();
        }
    }

}